// pages/cart/cart.js
import {
  ajaxFun
} from "../../utils/ajax"
Page({

  data: {
    page: 1,
    list: [],
    num: 0,
    choosenum: 0,
    allchoose: true,//全选开关
    total:0
  },
  onLoad() {
    this.getList(1)
  },

  async getList(page) { //获取购物车数据
    let result = await ajaxFun("/cart/list", "get", {
      isValid: true,
      page,
      limit: 10
    })
    this.setData({
      list: result.data.list
    }, function () {
      this.render()

    })

  },

  render() { //首次计算数量和选中数量
    let num = 0;//购物车商品总数量
    let choosenum = 0;//选中数量
    let total=0;//总价格
    this.data.list.map(item => {
      num += item.cartNum;
      if (item.attrStatus) {
        choosenum++;
        total+=item.price*item.cartNum
      }
    })

    if(choosenum==this.data.list.length){//选中的数量等于 数组的数量 可以全选
        this.setData({
          allchoose:true
        })
    }else{
      this.setData({
        allchoose:false
      })
    }
    this.setData({
      num,
      choosenum,
      total
    })
  },
  allchooseFun(){
      this.setData({
        allchoose:!this.data.allchoose
      })
  
      let listArry=this.data.list;
      listArry.map(item=>{
          item.attrStatus=this.data.allchoose
      })

      this.setData({
         list:listArry
      },function(){
         this.render()
      })

  },
  singleFun(e){
      console.log(e.target.dataset.index);
      let newArry=this.data.list;
      newArry[e.target.dataset.index].attrStatus= !newArry[e.target.dataset.index].attrStatus
      this.setData({
          list:newArry
      },function(){
         this.render()
      })
  
    },
    addFun(e){
      console.log(e.target.dataset.index);
      let newArry=this.data.list;
      newArry[e.target.dataset.index].cartNum++;
      this.setData({
         list:newArry
      },function(){
        this.render()
      })
    },
    reduceFun(e){
      console.log(e.target.dataset.index);
      let newArry=this.data.list;
      newArry[e.target.dataset.index].cartNum--;
      this.setData({
         list:newArry
      },function(){
        this.render()
      })
    }


})